package cn.edu.henu.team.ui_test;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.base.BaseActivity;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.bean.upLog;
import cn.edu.henu.team.utils.VpSwipeRefreshLayout;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static cn.bmob.v3.Bmob.getApplicationContext;

public class AllUploadLogActivity extends AppCompatActivity {
    private ImageView back;
    private VpSwipeRefreshLayout swipeRefreshLayout;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private ScrollView scrollView;
    private int count=0,num=4;

    private String objectId;

    //加载往期就医数据
    private ListView listView;
    private List<Map<String,Object>> data = new ArrayList<>();
    private SimpleAdapter simpleAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_upload_log);

        initView();
        initData();
        initClick();
    }

    protected void initView() {
        objectId = getIntent().getStringExtra("objectId");

        back =  findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        swipeRefreshLayout = findViewById(R.id.refresh);
        listView = findViewById(R.id.listview);
        scrollView = findViewById(R.id.scroll);
        if (scrollView != null) {
            scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                @Override
                public void onScrollChanged() {
                    if (swipeRefreshLayout != null) {
                        swipeRefreshLayout.setEnabled(scrollView.getScrollY() == 0);
                    }
                }
            });
        }
    }

    protected void initData() {
        //寻找创建时间最近的三篇文章
        BmobQuery<upLog> query = new BmobQuery("upLog");
        query.addWhereEqualTo("userID", objectId);
        query.order("-createdAt");
        query.include("user");
        query.setLimit(num);//返回三条数据
        query.setSkip(count);
        query.findObjects(new FindListener<upLog>() {
            @Override
            public void done(List<upLog> list, BmobException e) {
                if (e == null) {
                    if (list != null) {
                        for (upLog t : list) {
                            Map<String,Object> temp = new LinkedHashMap<>();
                            temp.put("objectId", t.getObjectId().toString());
                            temp.put("time",t.getTime().toString());
                            temp.put("location",t.getLocation().toString());
                            temp.put("answer",t.getAnswer().toString());
                            Log.d("**********",t.getObjectId().toString());
                            data.add(temp);
                        }
                        simpleAdapter = new SimpleAdapter(getApplicationContext(), data, R.layout.item_medical_record2, new String[] {"objectId","time","location","answer"}, new int[] {R.id.objectId, R.id.time, R.id.location, R.id.answer});
                        listView.setAdapter(simpleAdapter);
                        setListViewHeightBasedOnChildren();
                    }else{
                        Toast.makeText(getApplicationContext(), "已经没有数据啦", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "查询失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initClick() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            //控件停留两秒
                            Thread.sleep(2000);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    //更新数据
                                    data.clear();
                                    count+=num;
                                    initData();
                                    //停止
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // 点击获得该文章的objectId
                TextView t = v.findViewById(R.id.objectId);
                Intent it = new Intent(getApplicationContext(), FindLogActivity.class);
                it.putExtra("objectId", t.getText().toString());
                startActivity(it);
            }
        });
    }

    //动态修改listview高度，使得listview能完全展开
    private void setListViewHeightBasedOnChildren() {
        if (listView == null) {
            return;
        }
        if (simpleAdapter == null) {
            return;
        }
        int totalHeight = 0;
        //Toast.makeText(getApplication(), Integer.toString(simpleAdapter.getCount()), Toast.LENGTH_SHORT).show();
        for (int i = 0; i < simpleAdapter.getCount(); i++) {
            View listItem = simpleAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (simpleAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}